package com.financial.service.heemoney.service.impl;

import com.financial.service.heemoney.constants.FinancialPayHeemoneyEnumConstants;
import com.financial.service.heemoney.constants.FinancialPaysplitHeemoneyEnumConstants;
import com.financial.service.heemoney.constants.FinancialPaysplitHeemoneylogEnumConstants;
import com.financial.service.heemoney.convertor.HeemoneyPaySplitConvert;
import com.financial.service.heemoney.convertor.HeemoneyPaySplitQueryConvert;
import com.financial.service.heemoney.dao.FinancialPaysplitHeemoneyDao;
import com.financial.service.heemoney.dao.FinancialPaysplitHeemoneylogDao;
import com.financial.service.heemoney.domain.FinancialPaysplitHeemoneyDO;
import com.financial.service.heemoney.domain.FinancialPaysplitHeemoneylogDO;
import com.financial.service.heemoney.dto.HeemoneyConfigDTO;
import com.financial.service.heemoney.dto.businsess.HeemoneyPaySplitBusinessDTO;
import com.financial.service.heemoney.dto.businsess.HeemoneyPaySplitQueryBussinessDTO;
import com.financial.service.heemoney.dto.commmon.HeemoneyPaySplitCommonDTO;
import com.financial.service.heemoney.dto.commmon.HeemoneyPaySplitQueryCommonDTO;
import com.financial.service.heemoney.dto.inparameter.HeemoneyPaySplitInParamDTO;
import com.financial.service.heemoney.dto.inparameter.HeemoneyPaySplitQueryInParamDTO;
import com.financial.service.heemoney.dto.param.HeemoneyPaySplitParamDTO;
import com.financial.service.heemoney.dto.param.HeemoneyPaySplitQueryParamDTO;
import com.financial.service.heemoney.service.FinancialPaysplitHeemoneyService;
import com.financial.service.heemoney.utils.JsonUtils;
import com.financial.service.heemoney.utils.OkHttpUtils;
import com.financial.service.heemoney.utils.ResultUtils;
import com.financial.service.heemoney.utils.SignUtils;
import com.financial.service.heemoney.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class FinancialPaysplitHeemoneyServiceImpl implements FinancialPaysplitHeemoneyService {
    @Autowired
    private FinancialPaysplitHeemoneyDao financialPaysplitHeemoneyDao;

    @Autowired
    private HeemoneyConfigDTO heemoneyConfigDTO;
    @Autowired
    private OkHttpUtils okHttpUtils;
    @Autowired
    private FinancialPaysplitHeemoneylogDao financialPaysplitHeemoneylogDao;

    public static final Logger log = LoggerFactory.getLogger(FinancialWxconfigHeemoneylogServiceImpl.class);

    @Override
    public Map<String, Object> paySplit(HeemoneyPaySplitInParamDTO heemoneyPaySplitInParamDTO) {
        log.info("调用金融中心汇收银服务层付款分账接口前参数打印：{}", JsonUtils.beanToJson(heemoneyPaySplitInParamDTO));
        //请求参数日志保存
        this.savePaySplitlog(heemoneyPaySplitInParamDTO);
        //判断分账模式
        if (heemoneyPaySplitInParamDTO.getDivision_mode().equals(FinancialPaysplitHeemoneylogEnumConstants.ENUM_DIVISIONMODE_ONE)) {
            //数据转实体校验参数非空
            HeemoneyPaySplitCommonDTO heemoneyPaySplitCommonDTO = HeemoneyPaySplitConvert.MAPPER.configDTOConvertCommonDTO(new HeemoneyConfigDTO(), heemoneyPaySplitInParamDTO);
            HeemoneyPaySplitBusinessDTO heemoneyPaySplitBusinessDTO = HeemoneyPaySplitConvert.MAPPER.configDTOConvertBusinessDTO(new HeemoneyConfigDTO(), heemoneyPaySplitInParamDTO);
            HeemoneyPaySplitParamDTO heemoneyPaySplitParamDTO = new HeemoneyPaySplitParamDTO(heemoneyPaySplitCommonDTO, heemoneyPaySplitBusinessDTO);

            try {
                String resultStr = okHttpUtils.postJsonParams(new HeemoneyConfigDTO().getHeemoneyPayQuery().getRequest_url(), heemoneyPaySplitParamDTO.getJsonParam());
                log.info("http请求汇收银服务层付款分账接口回执:{}", resultStr);
                //解析数据并保存付款分账账户业务表
                this.savePaySplitDetail(heemoneyPaySplitInParamDTO, resultStr);
                //返回调用信息
                return ResultUtils.resultStr(resultStr);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("http请求汇收银服务层付款分账接口失败平台商户号为：{}", heemoneyPaySplitInParamDTO.getStore_no());
            }
        } else {
            //TODO 分账模式2 批量分账业务
            //按商户查询订单支付金额，满500元免手续费，不足500按一笔0.5元计算
            //queryMoney(heemoneyPaySplitInParamDTO);
            HeemoneyPaySplitCommonDTO heemoneyPaySplitCommonDTO = HeemoneyPaySplitConvert.MAPPER.configDTOConvertCommonDTO(new HeemoneyConfigDTO(), heemoneyPaySplitInParamDTO);
            //拼接业务参数
            HeemoneyPaySplitBusinessDTO heemoneyPaySplitBusinessDTO = new HeemoneyPaySplitBusinessDTO();
            heemoneyPaySplitBusinessDTO.setNotify_url(heemoneyConfigDTO.getHeemoneyPaySplit().getNotify_url());


            HeemoneyPaySplitParamDTO heemoneyPaySplitParamDTO = new HeemoneyPaySplitParamDTO(heemoneyPaySplitCommonDTO, heemoneyPaySplitBusinessDTO);


        }

        return ApiResult.failure();
    }

    @Override
    public Map<String, Object> splitAsyn(String str) {

        log.info("FinancialPaysplitHeemoneyServiceImpl---------------金融中心汇收银付款分账异步接口回执参数：{}", JsonUtils.beanToJson(str));
        //验证签名信息
        ApiResult apiResult = null;
        //封装返回值
        Map<String, Object> resultMap = new HashMap<>();
        try {
            boolean b = SignUtils.verifySign(str);
            log.info("FinancialPaysplitHeemoneyServiceImpl--------------汇收银商户付款分账异步回执签名验证结果：{}", b);

            Map<String, Object> changeMap = JsonUtils.jsonToMap(str);
            //解析返回值并保存异步回执
            this.saveAsynInfo(changeMap);

            //拼接调用者返回值
            resultMap.put("out_trade_no", changeMap.get("out_trade_no"));
            resultMap.put("mch_uid", changeMap.get("mch_uid"));
            resultMap.put("trade_status", changeMap.get("trade_status"));
            resultMap.put("success_bill_fee", changeMap.get("success_bill_fee"));
            resultMap.put("bill_fee", changeMap.get("bill_fee"));
            resultMap.put("bill_num", changeMap.get("bill_num"));
            resultMap.put("begin_time", changeMap.get("begin_time"));
            resultMap.put("success_bill_num", changeMap.get("success_bill_num"));

            return ApiResult.success(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("FinancialPaysplitHeemoneyServiceImpl---------汇收银付款分账异步回执返回失败");
        }
        return ApiResult.failure();
    }

    @Override
    public Map<String, Object> splitQuery(HeemoneyPaySplitQueryInParamDTO heemoneyPaySplitQueryInParamDTO) {
        log.info("FinancialPaysplitHeemoneyServiceImpl---------------金融中心汇收银付款分账查询接口参数：{}", JsonUtils.beanToJson(heemoneyPaySplitQueryInParamDTO));
        HeemoneyPaySplitQueryCommonDTO heemoneyPaySplitQueryCommonDTO = HeemoneyPaySplitQueryConvert.MAPPER.convertCommonDTO(new HeemoneyConfigDTO(), heemoneyPaySplitQueryInParamDTO);
        HeemoneyPaySplitQueryBussinessDTO heemoneyPaySplitQueryBussinessDTO = HeemoneyPaySplitQueryConvert.MAPPER.convertBusinessDTO(heemoneyPaySplitQueryInParamDTO);
        HeemoneyPaySplitQueryParamDTO heemoneyPaySplitQueryParamDTO = new HeemoneyPaySplitQueryParamDTO(heemoneyPaySplitQueryCommonDTO, heemoneyPaySplitQueryBussinessDTO);
        try {
            String resultStr = okHttpUtils.postJsonParams(new HeemoneyConfigDTO().getHeemoneyPayQuery().getRequest_url(), heemoneyPaySplitQueryParamDTO.getJsonParam());
            log.info("http请求汇收银服务层付款分账查询接口回执:{}", resultStr);
            //返回调用信息
            return ResultUtils.resultStr(resultStr);
        } catch (Exception e1) {
            e1.printStackTrace();
            log.error("http请求汇收银服务层付款分账查询失败付款单号为：{}", heemoneyPaySplitQueryInParamDTO.getOut_trade_no());
        }

        return ApiResult.failure();
    }

    @Override
    public Map<String, Object> queryMoney(String storeNo) {
        Map<String, Object> changeMap = new HashMap<>();
        changeMap.put("is_delete",FinancialPaysplitHeemoneylogEnumConstants.ENUM_ISDELETE_UNDEL);
        changeMap.put("store_no",storeNo);
        //changeMap.put("",);
        return financialPaysplitHeemoneylogDao.queryMoney(changeMap);
    }

    private void saveAsynInfo(Map<String, Object> changeMap) {
        FinancialPaysplitHeemoneyDO financialPaysplitHeemoneyDO = new FinancialPaysplitHeemoneyDO();
        financialPaysplitHeemoneyDO.setState(FinancialPaysplitHeemoneyEnumConstants.ENUM_STATE_SUC);
        financialPaysplitHeemoneyDO.setReturnMessage("SUCCESS");
        financialPaysplitHeemoneyDO.setOutTradeNo(changeMap.get("out_trade_no").toString());
        financialPaysplitHeemoneyDO.setBillNum(changeMap.get("bill_num").toString());
        financialPaysplitHeemoneyDO.setBillFee(changeMap.get("bill_fee").toString());

        financialPaysplitHeemoneyDao.save(financialPaysplitHeemoneyDO);

    }

    private void savePaySplitDetail(HeemoneyPaySplitInParamDTO heemoneyPaySplitInParamDTO, String resultStr) {
        FinancialPaysplitHeemoneyDO financialPaysplitHeemoneyDO = new FinancialPaysplitHeemoneyDO();

        Map<String, Object> changeMap = JsonUtils.jsonToMap(resultStr);
        String return_code = changeMap.get("return_code").toString();
        String result_code = changeMap.get("result_code").toString();
        if (return_code.equals("SUCCESS") && result_code.equals("SUCCESS")) {
            financialPaysplitHeemoneyDO.setReturnMessage(changeMap.get("result_msg").toString());
        } else {
            financialPaysplitHeemoneyDO.setReturnMessage(changeMap.get("error_msg").toString());
        }
        financialPaysplitHeemoneyDO.setIsDelete(FinancialPaysplitHeemoneyEnumConstants.ENUM_ISDELETE_UNDEL);
        financialPaysplitHeemoneyDO.setGmtCreate(new Date());
        financialPaysplitHeemoneyDO.setGmtModified(new Date());
        financialPaysplitHeemoneyDO.setResponseType(FinancialPaysplitHeemoneyEnumConstants.ENUM_RESPONSETYPE_SYNC);
        BeanUtils.copyProperties(heemoneyPaySplitInParamDTO, financialPaysplitHeemoneyDO);

        financialPaysplitHeemoneyDao.save(financialPaysplitHeemoneyDO);
    }

    private void savePaySplitlog(HeemoneyPaySplitInParamDTO heemoneyPaySplitInParamDTO) {

        FinancialPaysplitHeemoneylogDO paysplitHeemoneylogDO = new FinancialPaysplitHeemoneylogDO();
        paysplitHeemoneylogDO.setGmtModified(new Date());
        paysplitHeemoneylogDO.setGmtCreate(new Date());
        paysplitHeemoneylogDO.setIsDelete(FinancialPayHeemoneyEnumConstants.ENUM_ISDELETE_UNDEL);
        BeanUtils.copyProperties(heemoneyPaySplitInParamDTO, paysplitHeemoneylogDO);

        financialPaysplitHeemoneylogDao.save(paysplitHeemoneylogDO);

    }


    @Override
    public FinancialPaysplitHeemoneyDO get(Integer id) {
        return financialPaysplitHeemoneyDao.get(id);
    }

    @Override
    public List<FinancialPaysplitHeemoneyDO> list(Map<String, Object> map) {
        return financialPaysplitHeemoneyDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return financialPaysplitHeemoneyDao.count(map);
    }

    @Override
    public int save(FinancialPaysplitHeemoneyDO financialPaysplitHeemoney) {
        return financialPaysplitHeemoneyDao.save(financialPaysplitHeemoney);
    }

    @Override
    public int update(FinancialPaysplitHeemoneyDO financialPaysplitHeemoney) {
        return financialPaysplitHeemoneyDao.update(financialPaysplitHeemoney);
    }

    @Override
    public int remove(Integer id) {
        return financialPaysplitHeemoneyDao.remove(id);
    }

    @Override
    public int batchRemove(Integer[] ids) {
        return financialPaysplitHeemoneyDao.batchRemove(ids);
    }

}
